<?php

namespace App\Exports;

use App\Models\Download;
use App\Models\FrontendUser;
use App\Models\InvitationActivity;
use App\Models\InvitationRegister;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class InvitedUsersExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;
    public $product;

    public function __construct(Download $data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query() // 返回的数据
    {
        $activity = InvitationActivity::query()->find($this->request['activityId']);
        $register = InvitationRegister::query()->find($this->request['registerId']);

        return FrontendUser::query()
            ->with(['auth'])
            ->where('parent_id', $register->invite_id)
            ->where('created_at', '>=', $activity->start_time)
            ->where('created_at', '<=', $activity->end_time)
            ->orderByDesc('id');
    }

    public function map($value): array // 指定excel中每一列的数据字段
    {
        $value['nickname'] = drop_special_char($value['nickname']);

        return [
            $value['id'],
            $value['nickname'],
            $value['auth'] ? $value['auth']['real_name'] : '未实名',
            ' ' . $value['mobile'],
            $value['created_at'],
        ];
    }

    public function headings(): array // 指定excel的表头
    {
        return [
            'ID',
            '昵称',
            '真实姓名',
            '手机号',
            '注册时间',
        ];
    }
}
